<?php

namespace app\api\controller;

use app\common\model\imchat\Friends;
use app\common\model\UserCollect;
use ba\Date;
use Throwable;
use ba\Captcha;
use ba\Random;
use app\common\model\User;
use think\facade\Validate;
use app\common\facade\Token;
use app\common\model\UserScoreLog;
use app\common\model\UserMoneyLog;
use app\common\controller\Frontend;
use app\api\validate\Account as AccountValidate;

#[Apidoc\Title("账户中心 修改基本信息")]
class Account extends Frontend
{
    protected array $noNeedLogin = ['retrievePassword','overview'];

    protected array $noNeedPermission = ["*"];

    public function initialize(): void
    {
        parent::initialize();
    }

    #[
        Apidoc\Title("我的个人中心版本3.0"),
        Apidoc\Tag(""),
        Apidoc\Url("/api/account/overview"),
        Apidoc\Method("GET"),
        Apidoc\Return("json"),
        Apidoc\Returned("my_add", type: "int", desc: "我的发布", mock: "0"),
        Apidoc\Returned("my_fav", type: "int", desc: "我的收藏", mock: ""),
        Apidoc\Returned("my_attion", type: "int", desc: "我的关注", mock: ""),
        Apidoc\Returned("userinfo", type: "arr", desc: "我的信息", mock: ""),
        Apidoc\Returned("userinfo.isvip", type: "int", desc: "是否是会员0否1是 登录才返回到个人信息里面", mock: ""),
        Apidoc\Returned("userinfo.dodayview_items", type: "int", desc: "当天剩余查看次数", mock: ""),

    ]
    public function overview(): void
    {
        if($this->auth->isLogin()){
            $my_add = (new \app\common\model\Findstore())->where('user_id', $this->auth->id)
                ->count();

            $my_add2=(new \app\admin\model\Houses())->where('user_id', $this->auth->id)
                ->count();
            $my_add=$my_add+$my_add2;
            $my_fav = (new UserCollect())->where('user_id', $this->auth->id)->count();
            $my_attion = (new Friends())
                ->where([
                    ['from_uid','=', $this->auth->id],
                    ['to_uid','<>', 10]
                ])
                ->count();

            $userinfo=$this->auth->getUserInfo();
        }else{
            $my_add=0;
            $my_fav=0;
            $my_attion=0;
            $userinfo='';
        }

        $this->success('', [
            'my_add' => $my_add,
            'my_fav' => $my_fav,
            'my_attion' => $my_attion,
            'consumer_hotline'=>get_sys_config('consumer_hotline'),
            'userinfo'=>$userinfo,
            'wechat_qrcode'=>$this->request->domain().'/storage/qrcode_for_wechat.jpg'
        ]);
    }

    /**
     * 会员资料
     * @throws Throwable
     */
    #[
        Apidoc\Title("会员资料修改"),
        Apidoc\Tag("get获取基本信息 post提交修改基本信息"),
        Apidoc\Method("POST"),
        Apidoc\Param(name: "avatar", type: "string", require: false, desc: "头像", mock: "/upload/avatar.png"),
        Apidoc\Param(name: "nickname", type: "string", require: false, desc: "昵称", mock: "昵称"),
        Apidoc\Param(name: "gender", type: "string", require: false, desc: "性别:0=未知,1=男,2=女", mock: "2"),
        Apidoc\Param(name: "motto", type: "string", require: false, desc: "介绍", mock: "这人很懒，什么都没写"),
        Apidoc\Url("/api/account/profile"),
    ]
    public function profile(): void
    {
        if ($this->request->isPost()) {
            $data = $this->request->only(['id', 'avatar','nickname', 'gender', 'birthday', 'motto']);
            if (!isset($data['birthday'])) $data['birthday'] = null;

            try {
                $validate = new AccountValidate();
                $validate->scene('fixedit')->check($data);
            } catch (Throwable $e) {
                $this->error($e->getMessage());
            }
            $model = $this->auth->getUser();
            $model->startTrans();
            try {
                if(isset($data['motto'])){
                    $data['bio'] = trim($data['motto']);
                }
                $model->save($data);
                $model->commit();
            } catch (Throwable $e) {
                $model->rollback();
                $this->error($e->getMessage());
            }
            $this->success(__('Data updated successfully~'), [
                'userInfo' => $this->auth->getUserInfo()
            ]);
        }
        $this->success('基本信息', ['userinfo' => $this->auth->getUserInfo()]);
    }

    /**
     * 通过手机号或邮箱验证账户
     * 此处检查的验证码是通过 api/Ems或api/Sms发送的
     * 验证成功后，向前端返回一个 email-pass Token或着 mobile-pass Token
     * 在 changBind 方法中，通过 pass Token来确定用户已经通过了账户验证（用户未绑定邮箱/手机时通过账户密码验证）
     * @throws Throwable
     */
    public function verification(): void
    {
        $captcha = new Captcha();
        $params = $this->request->only(['type', 'captcha']);
        if ($captcha->check($params['captcha'], ($params['type'] == 'email' ? $this->auth->email : $this->auth->mobile) . "user_{$params['type']}_verify")) {
            $uuid = Random::uuid();
            Token::set($uuid, $params['type'] . '-pass', $this->auth->id, 600);
            $this->success('', [
                'type' => $params['type'],
                'accountVerificationToken' => $uuid,
            ]);
        }
        $this->error(__('Please enter the correct verification code'));
    }

    /**
     * 修改绑定信息（手机号、邮箱）
     * 通过 pass Token来确定用户已经通过了账户验证，也就是以上的 verification 方法，同时用户未绑定邮箱/手机时通过账户密码验证
     * @throws Throwable
     */
    public function changeBind(): void
    {
        $captcha = new Captcha();
        $params = $this->request->only(['type', 'captcha', 'email', 'mobile', 'accountVerificationToken', 'password']);
        $user = $this->auth->getUser();

        if ($user[$params['type']]) {
            if (!Token::check($params['accountVerificationToken'], $params['type'] . '-pass', $user->id, false)) {
                $this->error(__('You need to verify your account before modifying the binding information'));
            }
        } else {
            // 验证账户密码
            if (!isset($params['password']) || $user->password != encrypt_password($params['password'], $user->salt)) {
                $this->error(__('Password error'));
            }
        }

        // 检查验证码
        if ($captcha->check($params['captcha'], $params[$params['type']] . "user_change_{$params['type']}")) {
            if ($params['type'] == 'email') {
                $validate = Validate::rule(['email' => 'require|email|unique:user'])->message([
                    'email.require' => 'email format error',
                    'email.email' => 'email format error',
                    'email.unique' => 'email is occupied',
                ]);
                if (!$validate->check(['email' => $params['email']])) {
                    $this->error(__($validate->getError()));
                }
                $user->email = $params['email'];
            } elseif ($params['type'] == 'mobile') {
                $validate = Validate::rule(['mobile' => 'require|mobile|unique:user'])->message([
                    'mobile.require' => 'mobile format error',
                    'mobile.mobile' => 'mobile format error',
                    'mobile.unique' => 'mobile is occupied',
                ]);
                if (!$validate->check(['mobile' => $params['mobile']])) {
                    $this->error(__($validate->getError()));
                }
                $user->mobile = $params['mobile'];
            }
            Token::delete($params['accountVerificationToken']);
            $user->save();
            $this->success();
        }
        $this->error(__('Please enter the correct verification code'));
    }

    public function changePassword(): void
    {
        if ($this->request->isPost()) {
            $params = $this->request->only(['oldPassword', 'newPassword']);

            if (!$this->auth->checkPassword($params['oldPassword'])) {
                $this->error(__('Old password error'));
            }

            $model = $this->auth->getUser();
            $model->startTrans();
            try {
                $validate = new AccountValidate();
                $validate->scene('changePassword')->check(['password' => $params['newPassword']]);
                $model->resetPassword($this->auth->id, $params['newPassword']);
                $model->commit();
            } catch (Throwable $e) {
                $model->rollback();
                $this->error($e->getMessage());
            }

            $this->auth->logout();
            $this->success(__('Password has been changed, please login again~'));
        }
    }

    /**
     * 积分日志
     * @throws Throwable
     */
    public function integral(): void
    {
        $limit = $this->request->request('limit');
        $integralModel = new UserScoreLog();
        $res = $integralModel->where('user_id', $this->auth->id)
            ->order('create_time desc')
            ->paginate($limit);

        $this->success('', [
            'list' => $res->items(),
            'total' => $res->total(),
        ]);
    }

    /**
     * 余额日志
     * @throws Throwable
     */
    public function balance(): void
    {
        $limit = $this->request->request('limit');
        $moneyModel = new UserMoneyLog();
        $res = $moneyModel->where('user_id', $this->auth->id)
            ->order('create_time desc')
            ->paginate($limit);

        $this->success('', [
            'list' => $res->items(),
            'total' => $res->total(),
        ]);
    }

    /**
     * 找回密码
     * @throws Throwable
     */
    public function retrievePassword(): void
    {
        $params = $this->request->only(['type', 'account', 'captcha', 'password']);
        try {
            $validate = new AccountValidate();
            $validate->scene('retrievePassword')->check($params);
        } catch (Throwable $e) {
            $this->error($e->getMessage());
        }

        if ($params['type'] == 'email') {
            $user = User::where('email', $params['account'])->find();
        } else {
            $user = User::where('mobile', $params['account'])->find();
        }
        if (!$user) {
            $this->error(__('Account does not exist~'));
        }

        $captchaObj = new Captcha();
        if (!$captchaObj->check($params['captcha'], $params['account'] . 'user_retrieve_pwd')) {
            $this->error(__('Please enter the correct verification code'));
        }

        if ($user->resetPassword($user->id, $params['password'])) {
            $this->success(__('Password has been changed~'));
        } else {
            $this->error(__('Failed to modify password, please try again later~'));
        }
    }
}
